const url_microService = require('./common/config').url_microService;
//app.js
App({
  onLaunch: function() {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    let that = this;
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        let code = res.code
        this.globalData.code = code
        wx.getUserInfo({
          success: res => {
            that.globalData.userInfo = res.userInfo
            that.globalData.iv = res.iv
            that.globalData.encryptedData = res.encryptedData
            that.get3rdSession()
          }
        })
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  get3rdSession: function() {
    let that = this
    wx.request({
      url: url_microService + '/api/get3rd-session',
      data: {
        code: this.globalData.code
      },
      method: 'GET',
      success: res => {
        var sessionId = res.data.session;
        that.globalData.sessionId = sessionId
        wx.setStorageSync('sessionId', sessionId)
        that.decodeUserInfo()
      }
    })
  },
  decodeUserInfo: function() {
    let that = this
    wx.request({
      url: url_microService + '/api/decode-user-info',
      data: {
        encryptedData: this.globalData.encryptedData,
        iv: this.globalData.iv,
        session: wx.getStorageSync('sessionId')
      },
      method: 'GET',
      success: res => {
        that.globalData.userInfo = res.data;
        that.saveData();
      }
    })
  },
  saveData: function() {
    let that = this;
    var data = {
      openId: that.globalData.userInfo.openId,
      userName: '',
      nickName: that.globalData.userInfo.nickName,
      gender: that.globalData.userInfo.gender,
      avatarUrl: that.globalData.userInfo.avatarUrl
    }
    wx.request({
      url: url_microService + '/api/user',
      method: 'post',
      contentType: 'application/json;charset=utf-8',
      data: JSON.stringify(data),
      success: res => {
        console.log(res)
      }
    })
  },
  globalData: {
    userInfo: null,
    code: null,
    iv: null,
    encryptedData: null,
    sessionId: null
  }
})